package com.example.ivideo_2211a.fyt

import com.example.common.mvi.BaseRepository
import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.example.common.mvi.NetworkConfig
import com.example.ivideo_2211a.model.FtyTopeEntity

class FytRepository : BaseRepository() {
    fun getVideoListByChannelId(channelId: String, page: Int, pageSize: Int): Flow<NetworkResult<List<FytListData>>> {
        return safeApiCall {
            api.getSimpleVideoByChannelId(channelId, page, pageSize)
        }.map { result ->
            when (result) {
                is NetworkResult.Success -> {
                    val entity = result.data
                    if (entity.code == 200) {
                        NetworkResult.Success(entity.data)
                    } else {
                        NetworkResult.Error(Exception(entity.msg))
                    }
                }
                is NetworkResult.Error -> result
                is NetworkResult.Loading -> result
            }
        }
    }
    private val api: FytApi by lazy {
        Retrofit.Builder()
            .baseUrl("http://10.161.9.80:7015/") // TODO: 替换为实际baseUrl
            .client(NetworkConfig.createOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(NetworkConfig.createGson()))
            .build()
            .create(FytApi::class.java)
    }

    fun getSimpleType(): Flow<NetworkResult<List<FtyTopeEntity>>> {
        return safeApiCall {
            api.getSimpleType()
        }.map { result ->
            when (result) {
                is NetworkResult.Success -> {
                    val entity = result.data
                    if (entity.code == 200) {
                        val mapped = entity.data.map {
                            com.example.ivideo_2211a.model.FtyTopeEntity(
                                id = it.channelid, // 关键：用channelid
                                name = it.typename,
                                isSelected = false
                            )
                        }
                        NetworkResult.Success(mapped)
                    } else {
                        NetworkResult.Error(Exception(entity.msg))
                    }
                }
                is NetworkResult.Error -> result
                is NetworkResult.Loading -> result
            }
        }
    }
}
